<template>
  <div class="content">
    <div class="login">Log in</div>

    <div class="title">Welcome to SISU Audio Annotation!</div>
    <div class="title_dec">The online platform for speech-transcription alignment and annotation</div>

    <div class="form">
      <el-form ref="form" :rules="rules" :model="form">
        <el-form-item prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input type="password" show-password v-model="form.pass"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="btn" @click="submitForm('form')">Login</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="forgot_pass" @click="dialogVisible2 = true">Forgot your password</div>
    <div class="sign_up" @click="handleSignUpPage">New user? Sign up</div>




    <el-dialog :visible.sync="dialogVisible2" width="50%" :before-close="handleClose2">
      <el-form :model="ruleForm" :rules="rules2" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item class="bao_1" label="Email" prop="email" label-width="120px">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item class="bao_1" label="New Password" prop="password" label-width="120px">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false; ruleForm.password = ''; ruleForm.email = ''">Cancel</el-button>
        <el-button type="primary" @click="handleChange('ruleForm')">OK</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { login, modify_password } from "@/api/login.js"
export default {
  data() {
    let validateEmail = (rule, value, callback) => {
      let reg = /^[A-Za-z0-9-_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

      // 发送网络请求 获取邮箱返回值
      let emailBack = null
      if (value === '') {
        callback(new Error('Please enter your email address!!'));
      } if (!reg.test(value)) {
        callback(new Error('Please enter a correct email address!!'));
      } else if (value === emailBack) {
        //   发送网络请求，验证邮箱是否存在，不存在就报错
        callback(new Error('The mailbox already exists!!'));
      } else {
        callback()
      }
    };

    let validatePass = (rule, value, callback) => {
      // 发送网络请求判断密码是否正确
      if (value === '') {
        callback(new Error('Please enter a password!!'));
      } else {
        callback()
      }
    }

    let validatePass2 = (rule, value, callback) => {
      let regx = /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*().,。+-><]{6,18}$/;
      if (value === '') {
        callback(new Error('Please enter a password'));
      } else if (value.length < 6) {
        callback(new Error('A minimum of six digits is required'));
      } else if (!regx.test(value)) {
        callback(new Error('Must contain letters, numbers, special characters'));
      } else {
        callback();
      }
    }


    return {
      form: {
        // email: '23739111498@qq.com',
        // pass: 'sisu.aa12',
        email: '',
        pass: '',
      },
      rules: {
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      dialogVisible2: false, // 显示隐藏弹出框
      ruleForm: {
        email: '',
        password: '',
      },
      rules2: {
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
    }
  },
  methods: {
    handleClose2() {
      this.dialogVisible2 = false
      this.ruleForm.email = ''
      this.ruleForm.password = ''
    },
    handleChange(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modify_password({...this.ruleForm}).then(res => {
            const { code } = res || {}
            if (code == 200) {
              this.$message.success('The password was changed successfully')
            }
          }).catch(err => { console.log('err', err) })
          this.ruleForm.email = '';
          this.ruleForm.password = '';
          this.dialogVisible2 = false
        } else {
          return false
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          // console.log('发送网络请求', this.form)
          login({
            email: this.form.email,
            password: this.form.pass
          }).then(res => {
            const { code, data, message } = res;
            if (code == '200') {
              this.$message.success('Login successful');
              this.$store.commit('handleLogin', { data, router: this.$router })

              // 存到 localStorage 里面
              localStorage.setItem("login", JSON.stringify(data));
              let formLogin = {
                email: this.form.email,
                password: this.form.pass
              }
              localStorage.setItem("formLogin", JSON.stringify(formLogin));

            } else {
              this.$message.warning(`${message}`)
            }
          }).catch(err => {
            console.log('err', err)
          })
        } else {
          return false;
        }
      });
    },

    // 跳转到 注册页面
    handleSignUpPage() {
      // console.log('跳转')
      this.$router.push({ path: '/sign' })
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;

  .login {
    margin-top: 20px;
    padding-bottom: 3px;
    border-bottom: 3px solid #9c8bbf;
    font-weight: 700;
  }

  .title {
    margin-top: 20px;
    color: #bcb1d4;
    font-size: 24px;
    font-weight: 700;
  }

  .title_dec {
    margin-top: 5px;
    color: #d1cae1;
    font-size: 20px;
  }

  .form {
    margin-top: 50px;
    width: 400px;

    /deep/ .el-input__inner {
      border: 1px solid #e8ebed;
      width: 400px;
    }

    .btn {
      width: 400px;
      background: #baafd3;
      color: #fff;
    }
  }

  .forgot_pass {
    cursor: pointer;
    margin-bottom: 40px;
    padding-bottom: 3px;
    border-bottom: 2px solid #000;
  }

  .sign_up {
    cursor: pointer;
    padding-bottom: 3px;
    border-bottom: 2px solid #1c1c1c;
  }
}
</style>
